<script setup>
import {ref, watch} from 'vue'

const props = defineProps({
  // specs:所有的规格信息  skus:所有的sku组合信息
  goods: {
    type: Object,
    default: () => ({specs: [], skus: []})
  }
})

const emits = defineEmits(['change'])

// 存储当前选中的规格值
const selectedSpecs = ref({})

// 点击规格值时，更新当前选择的规格值
const clickSpecs = (spec, val) => {
  if (val.disabled) return

  // 更新选中的规格值
  selectedSpecs.value[spec.id] = val.id

  // 过滤出有效的 SKU 组合
  const newSkus = props.goods.skus.filter(sku => {
    return Object.keys(selectedSpecs.value).every(id => {
      return sku.specs.some(s => s.id === id && s.value_id === selectedSpecs.value[id])
    })
  })

  emits('change', newSkus)
}

// 监听 goods 变化时重置 selectedSpecs
watch(() => props.goods, () => {
  selectedSpecs.value = {}
})
</script>

<template>
  <div class="sku-view">
    <dl v-for="item in props.goods.specs" :key="item.id">
      <dt>
        {{ item.name }}：
      </dt>
      <dd>
        <div class="sku-item" v-for="(val, index) in item.values" :key="index">
          <img :src="val.picture"
               v-if="val.picture"
               :class="{ selected: val.selected === index, disabled: val.disabled }"
               @click="clickSpecs(item, val)" alt=""
          />
          <span v-else :class="{ selected: val.selected, disabled: val.disabled }"
                @click="clickSpecs(item, val)">
            {{ val.name }}
          </span>
        </div>
      </dd>
    </dl>
  </div>
</template>

<style scoped lang="scss">
.sku-view {


  dl {
    display: flex;
    align-items: center;
    margin-bottom: 10px;

    dt {
      width: 55px;
      color: #999;
    }

    dd {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      color: #666;
      cursor: pointer;

      .sku-item {
        margin: 5px;
        z-index: 1;

        img {
          width: 55px;
          height: 55px;
          border: 1px solid #ccc;

          &.selected {
            border-color: #27ba9b;
          }

          &:hover {
            border-color: #27ba9b;
          }
        }

        span {
          border: 1px solid #cccccc;
          display: inline-block;
          height: 30px;
          line-height: 28px;
          padding: 0 20px;
          margin: 5px;

          &:hover {
            border-color: #27ba9b;
          }

          &.disabled {
            opacity: 0.6;
            border-style: dashed;
            cursor: not-allowed;
          }
        }
      }
    }


  }
}
</style>
